import tinymce from 'tinymce/tinymce'
import store from '@/store'
import { revisionLineSwitch } from '@/api'

async function setRevisionLines(editor, newFlag) {
  await revisionLineSwitch(newFlag)

  // 先移除已有的修订线
  editor.dom.select('#tinymce>.page-wrapper .page-sheet .is-revised').forEach(node => {
    editor.dom.removeClass(node, 'is-revised')
  })

  // flag=0 原来没有修订线
  if (newFlag) {
    const revisionLineIds = store.state.xmleditor.revisionLineIds
    editor.dom
      .select('#tinymce>.page-wrapper .page-sheet [data-id]')
      .filter((node) => revisionLineIds.includes(node.dataset.id))
      .forEach((node) => editor.dom.addClass(node, 'is-revised'))
  }

  tinymce.activeEditor.notificationManager.open({
    timeout: 1500,
    text: '设置成功!',
    type: 'success'
  })
}

tinymce.PluginManager.add('docRevLine', function (editor) {
  editor.ui.registry.addMenuButton('docRevLine', {
    tooltip: '修订',
    icon: 'line',
    fetch: (cb) => cb([
      {
        type: 'togglemenuitem',
        text: '修订线',
        onAction: async (api) => {
          const flag = store.state.xmleditor.enableRevisionLine
          store.commit('xmleditor/SET_REVISION_LINE_ENABLE', !flag)
          api.setActive(!flag)
          await setRevisionLines(editor, !flag)
        },
        onSetup: (api) => {
          api.setActive(store.state.xmleditor.enableRevisionLine)
        }
      },
      {
        type: 'togglemenuitem',
        text: '重新修订',
        onAction: async () => {
          await setRevisionLines(editor, true)
        },
        onSetup: (api) => {
          api.setDisabled(!store.state.xmleditor.enableRevisionLine)
        }
      }
    ])
  })


  return {
    getMetadata: function () {
      return {
        name: '修订线',
        url: 'http://sfrj.cn'
      }
    }
  }
})
